﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using EzDesk.Apps.Model.Attendance;
using EzDesk.Clients.MobileWeb.AttendanceService;
using EzDesk.Utility.Extensions;
using EzDesk.Utility.Log;
using EzDesk.Utility.Web.Controllers;
using EzDesk.Utility.Web.Extensions;
using EzDesk.Utility.Web.ServiceReference;

namespace EzDesk.Clients.MobileWeb.Controllers
{
    public class AttendanceController : EzDeskAppController
    {
        static IAttendanceService AttendanceService
        {
            get { return ServiceReferenceFactory<IAttendanceService, AttendanceServiceClient>.GetService(); }
        }
        
        // GET: /Attendance/AuditLeave
        public ActionResult AuditLeave(Guid leaveId)
        {
            LeaveInfo leaveInfo = AttendanceService.GetLeaveInfoById(leaveId);

            return View(leaveInfo);
        }

        /// <summary>
        /// 批准假期
        /// </summary>i
        /// <returns></returns>
        [HttpPost]
        [ValidateInput(false)]

        public ActionResult DoAuditLeave(Guid leaveInfoId, string auditText, string auditType)
        {
            auditText = Server.HtmlEncode(auditText);
            try
            {
                AttendanceService.AuditLeave(leaveInfoId, auditType == "同意", auditText, CurrentUserId);
            }
            catch (Exception ex)
            {
                LogEx.ERROR("[MobileWeb - Attendance]", "审核时出现错误。", ex);
            }

            SetReturnInfoText("审核成功。");
            return RedirectToAction("Index", "Home");
        }


        /// <summary>
        /// 显示个人某一天的考勤情况
        /// </summary>
        /// <param name="time">要显示的时间，Epoch格式</param>
        /// <returns></returns>
        [Authorize]
        [HttpGet]
        public ActionResult PersonalAttendanceInfoPerDay(int? time)
        {
            // 获取页面要显示的内容日期
            DateTime date = DateTime.Now.Date;
            if (time != null)
            {
                date = EpochDateTimeExtension.FromEpoch(time.Value);
            }

            var userId = CurrentUserId;

            //当日日期
            var currentDate = DateTime.Now.Date;

            var dayInfo = AttendanceService.GetDayInfo(userId, date);

            bool isDisplayAttendanceInfo = true;
            bool isDisplayApplyEvaluation = true;
            bool isDisplayEvaluationInfo = true;

            //如果是当日 修改旷工为否
            if (currentDate < dayInfo.Date)
            {
                isDisplayAttendanceInfo = false;
            }


            // 获取正在提交中的评估修改申请
            var modifyAttendanceApplication = AttendanceService.GetCurrentEvaluationModifyApplication(userId, date);

            //如果已经申请修改或者是当天,不可再次申请
            if (modifyAttendanceApplication != null // 当前已有正在处理的申请，则不能再申请
                || currentDate == dayInfo.Date  // 不能申请当天的评估修改
                )
            {
                isDisplayApplyEvaluation = false;
            }

            // 不显示当天的考勤评估信息
            if (currentDate == dayInfo.Date)
            {
                isDisplayEvaluationInfo = false;
            }


            // 当日考勤详细信息
            var dayAttendanceDetail = new DayAttendnaceInfoDetailModel()
            {
                TargetUser = EzApiClient.GetSimpleUserById(userId),
                AttendanceInfoList =
                    AttendanceService.GetAttendanceInfoListByUserInDay(date, userId,
                                                                        null),
                LeaveInfo = AttendanceService.GetDayLeaveInfo(userId, date)
            };

            if (isDisplayEvaluationInfo)
            {
                dayAttendanceDetail.AttendanceEvaluation =
                    AttendanceService.GetDayAttendanceEvaluation(userId, date);
            }


            // 获得考勤评估修改的历史信息
            var evaluationModifyHistory = AttendanceService.GetEvaluationModifyHistory(userId, date);


            ViewData["DayInfo"] = dayInfo;
            ViewData["IsDisplayAttendanceInfo"] = isDisplayAttendanceInfo;

            if (isDisplayAttendanceInfo)
            {
                ViewData["IsDisplayApplyEvaluation"] = isDisplayApplyEvaluation;
                ViewData["IsDisplayEvaluationInfo"] = isDisplayEvaluationInfo;

                // 显示考勤相关信息
                ViewData["DayAttendanceDetail"] = dayAttendanceDetail;

                // 考勤评估的修改历史
                ViewData["EvaluationModifyHistory"] = evaluationModifyHistory;
            }

            return View();
        }



        //
        // POST: /Attendance/ApplyModifyAttendanceEvaluation
        /// <summary>
        /// 提交修改考勤评估的申请
        /// </summary>
        /// <returns></returns>
        [Authorize]
        [HttpPost]
        public ActionResult ApplyModifyAttendanceEvaluation(
            int date,
            string applyText
            )
        {
            try
            {
                DateTime theDate = EpochDateTimeExtension.FromEpoch(date);
                AttendanceService.ApplyEvaluationModify(
                    CurrentUserId,
                    theDate,
                    applyText
                    );

            }
            catch (Exception ex)
            {
                LogEx.ERROR("[MobileWeb - Attendance]", "申请失败。", ex);
            }

            SetReturnInfoText("申请成功。");
            return RedirectToAction("PersonalAttendanceInfoPerDay",
                new
                {
                    time = date
                });

        }


    }
}
